package cn.thens.kdroid.sample.test

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.GridLayoutManager
import cn.thens.kdroid.sample.R
import cn.thens.kdroid.sample.launcher.AppItemAdapter
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_test_refresh.*
import java.util.concurrent.TimeUnit

class TestRefreshActivity : AppCompatActivity() {
    private val appItemAdapter by lazy { AppItemAdapter() }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_test_refresh)

        vList.adapter = appItemAdapter
        vList.layoutManager = GridLayoutManager(this, 4)
        appItemAdapter.refill(AppItemAdapter.getAppList(this))
        vRefreshLayout.setOnRefreshListener {
            Observable.timer(1, TimeUnit.SECONDS, Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnComplete {
                    val appList = AppItemAdapter.getAppList(this)
                    appItemAdapter.refill(appList)
                    vRefreshLayout.finishRefresh()
                }
                .subscribe()
        }
        vRefreshLayout.setOnLoadmoreListener {
            Observable.timer(1, TimeUnit.SECONDS, Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnComplete {
                    val appList = AppItemAdapter.getAppList(this)
                    appItemAdapter.addAll(appList)
                    appItemAdapter.notifyChanged()
                    vRefreshLayout.finishLoadmore()
                }
                .subscribe()
        }
    }

    override fun onResume() {
        super.onResume()
    }

    fun testError() {
        Thread { makeError() }.start()
        makeError()
    }

    fun makeError() {
        val list = ArrayList<Int>()
        list[1]
    }
}